package com.ziytek.web.citizen.controller;

import com.ziytek.web.citizen.constant.ApiConstant;
import com.ziytek.web.citizen.constant.NumConstant;
import com.ziytek.web.citizen.constant.ServerConstant;
import com.ziytek.web.citizen.constant.SettingConstant;
import com.ziytek.web.citizen.enums.ResponseEnum;
import com.ziytek.web.citizen.model.req.LogInReq;
import com.ziytek.web.citizen.model.req.LogOutReq;
import com.ziytek.web.citizen.model.req.UserAddReq;
import com.ziytek.web.citizen.model.req.UserDelReq;
import com.ziytek.web.citizen.model.rsp.LogInResponse;
import com.ziytek.web.citizen.model.rsp.LogOutResponse;
import com.ziytek.web.citizen.model.rsp.UnifyResponse;
import com.ziytek.web.citizen.pojo.basic.UserLogin;
import com.ziytek.web.citizen.service.itf.LoginService;
import com.ziytek.web.citizen.util.StringUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户接口
 *
 * @author fenghx
 * @version 1.0
 * @className LoginController
 * @date 2023/12/7 16:51
 **/
@Slf4j
@RestController
@RequestMapping(ApiConstant.API_CABINET)
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class LoginController {
    private final LoginService loginService;

    /**
     * 用户登录
     *
     * @param login 登录请求参数（JSON Body）
     * @return LogInResponse description: 返回登录信息
     * @apiNote 请求示例:
     * {
     * "userName": "admin",
     * "userPassword": "123456"
     * }
     * @apiNote 响应示例:
     * <pre>{@code
     * "retCode": "0",
     * "retMsg": "成功",
     * "token":"1122",
     * "role":"admin"
     * }
     * }</pre>
     */
    @PostMapping(ApiConstant.LOG_IN)
    public LogInResponse logIn(@Valid @RequestBody LogInReq login) {
        log.info("user login request:{}", login);
        return loginService.login(login.getUserName(), login.getUserPassword());
    }

    /**
     * 用户退出
     *
     * @param loginOut 退出请求参数（JSON Body）
     * @return LogOutResponse description: 返回退出信息
     */
    @PostMapping(ApiConstant.LOG_OUT)
    public LogOutResponse logOut(@RequestBody LogOutReq loginOut) {
        log.info("loginOut request:{}", loginOut);
        var response = new LogOutResponse();
        response.setRetCode(ServerConstant.ERROR);

        if (ServerConstant.STRING_NULL.equalsIgnoreCase(loginOut.getToken())) {
            response.setRetCode(ServerConstant.SUCCESS);
            response.setRetMsg("退出成功");
            return response;
        }

        if (StringUtil.isEmpty(loginOut.getToken()) || ServerConstant.STRING_NULL.equalsIgnoreCase(loginOut.getToken())) {
            response.setRetCode(ServerConstant.ERROR);
            response.setRetMsg("token不能为空");
            return response;
        }

        boolean logOutSuccess = loginService.logOut(loginOut.getToken());
        if (!logOutSuccess) {
            response.setRetMsg("退出失败");
            return response;
        }

        response.setRetCode(ServerConstant.SUCCESS);
        response.setRetMsg("退出成功");
        return response;
    }

    /**
     * 新增用户
     *
     * @param request 新增请求参数（JSON Body）
     * @return UnifyResponse description: 新增用户响应信息
     */
    @PostMapping(ApiConstant.USER_ADD)
    public UnifyResponse userAdd(@RequestBody UserAddReq request) {
        log.info("UserAddReq request:{}", request);
        var response = new UnifyResponse();
        response.setRetCode(ServerConstant.ERROR);

        if (StringUtil.isEmpty(request.getUserName()) || StringUtil.isEmpty(request.getUserPassword())) {
            response.setRetMsg("用户名或密码不能为空");
            return response;
        }

        var login = new UserLogin();
        login.setUserName(request.getUserName());
        login.setUserPassword(request.getUserPassword());
        login.setAvailable(SettingConstant.IS_AVAILABLE);
        login.setCreateTime(System.currentTimeMillis());
        login.setUpdateTime(System.currentTimeMillis());
        login.setLastLoginInTime(System.currentTimeMillis());
        login.setLastLoginOutTime(System.currentTimeMillis());
        login.setRole(!StringUtil.isEmpty(request.getRole()) && ResponseEnum.ROLE_ADMIN.getCode().equals(request.getRole()) ?
                ResponseEnum.ROLE_ADMIN.getCode() : ResponseEnum.ROLE_USER.getCode());

        var addUserSuccess = loginService.addLogin(login);
        if (addUserSuccess <= NumConstant.INT_ZERO) {
            response.setRetMsg("用户新增失败");
            return response;
        }

        response.setRetCode(ServerConstant.SUCCESS);
        response.setRetMsg("用户新增成功");
        return response;
    }

    /**
     * 用户删除
     *
     * @param request 删除请求参数（JSON Body）
     * @return UnifyResponse description: 删除用户响应信息
     */
    @PostMapping(ApiConstant.USER_DELETE)
    public UnifyResponse userDelete(@RequestBody UserDelReq request) {
        log.info("userDelete request:{}", request);
        var response = new UnifyResponse();
        response.setRetCode(ServerConstant.ERROR);

        if (request.getId() == null) {
            response.setRetMsg("用户主键ID不能为空");
            return response;
        }

        var login = new UserLogin();
        login.setId(request.getId());

        int addUserSuccess = loginService.deleteLogin(login);
        if (addUserSuccess <= NumConstant.INT_ZERO) {
            response.setRetMsg("用户删除失败");
            return response;
        }

        response.setRetCode(ServerConstant.SUCCESS);
        response.setRetMsg("用户删除成功");
        return response;
    }
}
